package com.magic.process;

import com.magic.dto.MeetingDTO;
import com.magic.enums.MeetingEventEnum;
import com.magic.handler.MeetingHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author magic
 * @version 1.0
 * @date 2022/2/22 14:52
 */
@Slf4j
public abstract class BaseMeetingEvent<T> implements IMeetingEvent<T> {

  private List<IMeetingOperator> operatorList;

  @Override
  public IMeetingEvent<T> bindEventOperator(List<IMeetingOperator> operatorList) {
    this.operatorList = operatorList;
    return this;
  }

  @Override
  public MeetingDTO[] executeEvent(T param) {
    MeetingEventEnum currentEvent = this.currentEvent(param);
    log.debug("执行会议事件event{} param={}",currentEvent, param);
    MeetingHelper[] helpers = this.preExecute(param);
    if(helpers != null && helpers.length > 0) {
      for(MeetingHelper helper: helpers) {
        if(helper != null) {
          helper.setCurrentEvent(currentEvent);
        }
      }
    } else {
      log.warn("当前操作未生成有效的 IMeetingDTO，param = {}", param);
    }
    if (!CollectionUtils.isEmpty(operatorList)) {
      for (IMeetingOperator operator : operatorList) {
        if(operator != null && operator.support(currentEvent)) {
          operator.beforeEvent(currentEvent, helpers);
        }
      }
    }
    this.execute(currentEvent, helpers);
    if (!CollectionUtils.isEmpty(operatorList)) {
      for (IMeetingOperator operator : operatorList) {
        if(operator != null && operator.support(currentEvent)) {
          try {
            operator.afterEvent(currentEvent, helpers);
          } catch (Exception e) {
            log.error("{} after process operator error: ", e, operator.getClass().getName());
          }
        }
      }
    }
    List<MeetingDTO> meetingDTOS =
            Arrays.stream(helpers).map(help -> help.getMeetingDTO()).collect(Collectors.toList());
    return meetingDTOS.toArray(new MeetingDTO[meetingDTOS.size()]);
  }
}
